package org.example.security;

import org.example.service.impl.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 访问其它控制器的时候判断权限，判断前端是否传了token，穿了之后从redis中找出来
 */
@Component
//OncePerRequestFilter 匹配每个请求
public class TokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String token=httpServletRequest.getHeader("token");
        if (StringUtils.hasText(token)){
            // 传了token，看看对不对，根据传的对象把token找回来
            UserDetailsImpl loginUser=tokenService.getLoginUser(token);
            // 找回来之后，存到security上下文里面去，好做权限判断
            UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(loginUser,loginUser.getPassword(), loginUser.getAuthorities());
            // 自动找名字密码，匹配权限
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);// 没有传token就放行，放行之后security就会检查是登录还是注销，检查你的权限
    }
}
